package com.example.wlzz.crawler;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.alibaba.fastjson.JSON;
import com.example.wlzz.dto.*;
import com.example.wlzz.enums.ResultEnum;
import com.example.wlzz.utils.ResultVOUtil;
import com.example.wlzz.utils.StrToListForIntUtil;
import com.example.wlzz.vo.ResultVO;
import net.sf.json.JSONObject;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.util.StringUtils;

public class LoginPage {     //临沂大学爬虫
    public Map<String, String> getCookie(String url) throws Exception { //第一次访问只为了获取cookies
        Connection con = Jsoup.connect(url);
        con.header("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");// 配置模拟浏览器
        Response rs = con.execute();// 获取响应
        return rs.cookies();
    }
    //进行登陆页面
    public ResultVO login(String userName, String pwd, String code, Map<String, String> cookies) {
        Map<String, String> datas = new HashMap<>();  //参数
        datas.put("RANDOMCODE", code); //验证码
        try {
            String encoded = getEncoded(userName, pwd, cookies);  //模拟前端加密得到数据
            datas.put("encoded", encoded);
//            Connection con2 = Jsoup
//                    .connect("http://211.64.240.25/jxd/xk/LoginToXk");
            Connection con2 = Jsoup
                    .connect("http://jwxt.lyu.edu.cn/jxd/xk/LoginToXk");
            con2.header("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
            // 设置cookie和post上面的map数据
            Response login = con2.ignoreContentType(true)
                            .method(Method.POST)
                            .data(datas).cookies(cookies)
                            .timeout(10000)
                            .followRedirects(false)
                            .ignoreHttpErrors(true)
                            .execute();
             System.out.println(login.body());
            //Document document = login.parse();
            ;  //登陆成功是否有名字
            System.out.println("临沂登录后的状态码："+login.statusCode());
            if (login.statusCode()==302) {
                CookieDTO cookieDTO = new CookieDTO();
                cookieDTO.setCookies("JSESSIONID=" + cookies.get("JSESSIONID"));
                return ResultVOUtil.success(cookieDTO);
            } else {
                return ResultVOUtil.error(ResultEnum.SNO_ERROR.getCode(), ResultEnum.SNO_ERROR.getMessage());
            }
        }catch(Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.LOGIN_SCHOOL_ERROR.getCode(),ResultEnum.LOGIN_SCHOOL_ERROR.getMessage());

        }
    }
    public ResultVO getKlassCard(Map<String, String> cookies,String xnxq01id){  //根据日期获得学期理论课表

//        Connection getData = Jsoup.connect("http://211.64.240.25/jxd/xskb/xskb_list.do");
         Connection getData = Jsoup
                .connect("http://jwxt.lyu.edu.cn/jxd/xskb/xskb_list.do");
        getData.header("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
        Map<String,String> datas = new HashMap<>();
        datas.put("xnxq01id",xnxq01id);
        try {
            Response data = getData.ignoreContentType(true).method(Method.GET).data(datas).cookies(cookies).timeout(10000).execute();
            Document document = data.parse();
            Elements trElements =document.getElementById("kbtable").getElementsByTag("tr");
            List<NewKlassContent> klassContentList = new ArrayList<>();
            for (int i = 1; i < trElements.size() - 2; i++) {  //一行一行来
                Elements tdElements = trElements.get(i).select("td"); //对每一行的列进行操作
                int week = 1;
                for (int j = 0; j < tdElements.size(); j++) {
                    String klassContent = tdElements.get(j).select("div").get(1).text();  //学期理论课表
                    if (!"".equals(klassContent)) {
                        System.out.println("课程："+klassContent);
                        String[] klassContentArray = klassContent.split(" --------------------- ");  //不管有没有都区分
                        for (String s : klassContentArray) {
                            NewKlassContent newKlassContent = new NewKlassContent();
                            newKlassContent.setDay(week);
                            newKlassContent.setStart((2*i-1));
                            newKlassContent.setStep(2);  //固定持续两节
                            String[] arrayStr = s.split(" ");
                            newKlassContent =  getNewKlassContent(newKlassContent,arrayStr);
                            klassContentList.add(newKlassContent);
                        }
                    }
                    week++;
                }
            }
            return ResultVOUtil.success(klassContentList);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.GET_CLASS_ERROR.getCode(),ResultEnum.GET_CLASS_ERROR.getMessage());
        }
    }
   public List<MajorKlassContent> getMajorKlass(Map<String,String> cookies, Map<String,String> datas)
                throws Exception{

       Connection con = Jsoup
               .connect("http://jwxt.lyu.edu.cn/jxd/kbcx/kbxx_xzb_ifr");
//       Connection con = Jsoup.connect("http://211.64.240.25/jxd/kbcx/kbxx_xzb_ifr");
       con.header("User-Agent",
               "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");// 配置模拟浏览器
       Connection.Response rs = con.ignoreContentType(true).method(Method.POST).data(datas).cookies(cookies).execute();// 获取响应
       Document document = Jsoup.parse(rs.body());
       //System.out.println(document.body().toString());
       Element kbtable = document.getElementById("kbtable");
       Elements tr = kbtable.getElementsByTag("tr");
       int[] week = {1,2,3,4,5,6,7};  //星期
       int[] klass = {1,2,3,4,5};  //课程
       int weekNumber = 0;     //星期序号
       int klassNumber = 0;  //课程序号
       List<MajorKlassContent> majorKlassContents = new ArrayList<>();   //List的Major
       for (int i = 2;i<tr.size();i++){
           Elements elementsTd =  tr.get(i).getElementsByTag("td");
           MajorKlassContent majorKlassContent = new MajorKlassContent();
           List<NewKlassContent> majorKlassArrayList = new ArrayList<>();
           for (int j = 1;j<elementsTd.size();j++){
               if(klassNumber==5){   //越界
                   klassNumber = 0;
                   ++weekNumber;
               }
               if(weekNumber==7){
                   weekNumber=0;  //换行重置星期
               }
               if (!"".equals(elementsTd.get(j).text())) {

                        NewKlassContent newKlassContent = new NewKlassContent();
                        newKlassContent.setDay(week[weekNumber]);    //星期几
                        newKlassContent.setStart(2 * klass[klassNumber] - 1);  //开始节
                        newKlassContent.setStep(2); //节长
                        String klassContent = elementsTd.get(j).text();  //课程
                        System.out.print("课程：" + klassContent);
                        String[] array = klassContent.split(" ");  //0为课程名，1为老师名，2为周次，3为教室
                        if(array[1].indexOf("[外教]")!=-1){   //[外教]  (1-16周)
                                newKlassContent.setTeacher(klassContent.substring(klassContent.indexOf("[外教]"),klassContent.indexOf("(1-16周)")));
                                newKlassContent.setRoom(array[array.length-1]);
                                newKlassContent.setName(array[0]);
                                List<Integer> list1 = Stream.iterate(1, item -> item+1).limit(16).collect(Collectors.toList());
                                newKlassContent.setWeekList(list1);
                                majorKlassArrayList.add(newKlassContent);
                        }else{
                            if(array.length==4){
                                System.out.println("\t" + array.length);
                                newKlassContent.setName(array[0]);
                                newKlassContent.setTeacher(array[1]);
                                if (array.length < 4) {
                                    newKlassContent.setRoom("");
                                } else {
                                    newKlassContent.setRoom(array[3]);
                                }

                                String subweeks = array[2];  //(1-16周)
                                List<Integer> weekList = new ArrayList<>();
                                if(subweeks.indexOf("-")==-1){   //没有  - 表示单周    (1周)
                                    int leftLocation = subweeks.indexOf("(");
                                    int rightLocation = subweeks.indexOf("周");
                                    String singleWeek = subweeks.substring(leftLocation+1,rightLocation);
                                    weekList.add(Integer.valueOf(singleWeek));
                                }else{
                                    if(subweeks.indexOf(",")!=-1){ //(1-8,12-16周)
                                        String[] splitStr = subweeks.split(",");
                                        String number1 = splitStr[0].substring(1,2);
                                        String number2 = splitStr[0].substring(3,4);
                                        String number3 = splitStr[1].substring(0,2);
                                        String number4 = splitStr[1].substring(3,5);
                                        List<Integer> list1 = Stream.iterate(Integer.valueOf(number1), item -> item+1).limit(Integer.valueOf(number2)-Integer.valueOf(number1)+1).collect(Collectors.toList());
                                        List<Integer> list2 = Stream.iterate(Integer.valueOf(number3), item -> item+1).limit(Integer.valueOf(number4)-Integer.valueOf(number3)+1).collect(Collectors.toList());
                                        weekList.addAll(list1);
                                        weekList.addAll(list2);
                                    }else{
                                        String weekStr = subweeks.substring(1, 5);
                                        String[] weekArray = weekStr.split("-");
                                        int endFor;
                                        if (weekArray[1].indexOf("周") != -1) {  //说明结尾是个位数
                                            endFor = Integer.valueOf(weekArray[1].substring(0, 1));
                                        } else {
                                            endFor = Integer.valueOf(weekArray[1]);
                                        }
                                        for (int z = Integer.valueOf(weekArray[0]); z <= endFor; z++) {
                                            if (array[2].indexOf("单") != -1) {
                                                if (2 * z - 1 <= 16) {
                                                    weekList.add(2 * z - 1);  //1,3,5,7,9...
                                                }
                                            } else if (array[2].indexOf("双") != -1) {
                                                if (2 * z <= 16) {
                                                    weekList.add(2 * z);  //2，4，6，8....
                                                }
                                            } else {
                                                weekList.add(z);
                                            }
                                        }
                                    }
                                }
                                newKlassContent.setWeekList(weekList);
                                majorKlassArrayList.add(newKlassContent);
                        }
                            if(array.length==8){  //说明他妈的还有其他课   //还不止
                                NewKlassContent newKlassContent2 = new NewKlassContent();
                                newKlassContent2.setDay(week[weekNumber]);    //星期几
                                newKlassContent2.setStart(2*klass[klassNumber]-1);  //开始节
                                newKlassContent2.setStep(2); //节长
                                newKlassContent2.setName(array[4]);
                                newKlassContent2.setTeacher(array[5]);
                                newKlassContent2.setRoom(array[7]);
                                String subweeks2 = array[6];  //(1-16周)
                                String weekStr2 = subweeks2.substring(1,5);
                                String[] weekArray2 = weekStr2.split("-");
                                List<Integer> weekList2 = new ArrayList<>();
                                int endFor2;
                                if(weekArray2[1].indexOf("周")!=-1){  //说明结尾是个位数
                                    endFor2 = Integer.valueOf(weekArray2[1].substring(0,1));
                                }else{
                                    endFor2 = Integer.valueOf(weekArray2[1]);
                                }
                                for(int h = Integer.valueOf(weekArray2[0]);h<=endFor2;h++){
                                    if(array[6].indexOf("单")!=-1){
                                        if(2*h-1<=16){
                                            weekList2.add(2 * h -1);  //1,3,5,7,9...
                                        }
                                    }else if(array[6].indexOf("双")!=-1){
                                        if(2*h<=16){
                                            weekList2.add(2 * h);  //2，4，6，8....
                                        }
                                    }else{
                                        weekList2.add(h);
                                    }
                                }
                                newKlassContent2.setWeekList(weekList2);
                                majorKlassArrayList.add(newKlassContent2);
                            }
                       }


               }
                 ++klassNumber;   //自增
           }   //第一层for
           majorKlassContent.setMajor(elementsTd.get(0).text());
           majorKlassContent.setNewKlassContentList(majorKlassArrayList);
           majorKlassContents.add(majorKlassContent);
       }
        return majorKlassContents;
  }
    public String getEncoded(String xh,String pwd,Map<String, String> cookie)throws Exception{  //模拟前端加密
        Connection getData = Jsoup
                .connect("http://jwxt.lyu.edu.cn/jxd/xk/LoginToXk?flag=sess");
     //   Connection getData = Jsoup.connect("http://211.64.240.25/jxd/xk/LoginToXk?flag=sess");
        getData.header("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
        Response data =  getData.ignoreContentType(true).method(Method.POST).cookies(cookie).timeout(10000).execute();
        String str =data.body().toString();
        JSONObject jsonObject = JSONObject.fromObject(str);
        String urlData = jsonObject.getString("data");   //通过url得到的data
        System.out.println("urlData:  "+urlData);
        String scode = urlData.split("#")[0];
        String sxh = urlData.split("#")[1];
        String code = xh + "%%%"+pwd;
        StringBuilder encoded  = new StringBuilder();
        for(int i = 0;i<code.length();i++){
            if(i<20){
                encoded.append(code.substring(i,i+1)+scode.substring(0,Integer.parseInt(sxh.substring(i,i+1))));
                scode = scode.substring(Integer.parseInt(sxh.substring(i,i+1)),scode.length());
            }else{
                encoded.append(code.substring(i,code.length()));
                i=code.length();
            }
        }
        return encoded.toString();
    }



    public static NewKlassContent getNewKlassContent(NewKlassContent newKlassContent,String[] arrayStr){  //单课程加工厂
        //正常来说  ->  //0为课程名，1为老师名，2为周次，3为教室    但是可能存在外教多个空ge
        if(arrayStr[1].indexOf("外教")!=-1){  //存在外教，那就存在多个空格
            newKlassContent.setName(arrayStr[0]);
            int error = arrayStr.length-4;  //误差
            String  teacherName="";
            if(error>0){  //一般来说是等于0的,这说明外教佬有空格
                for(int i = 1;i<=error+1;i++){
                    teacherName+=arrayStr[i];
                }
                newKlassContent.setName(arrayStr[0]);
                newKlassContent.setTeacher(teacherName);
                newKlassContent.setRoom(arrayStr[3+error]);
                newKlassContent.setWeekList(getIntergeList(arrayStr[2+error]));


            }else{//外教佬没单个单词
                newKlassContent.setTeacher(arrayStr[1]);
                newKlassContent.setWeekList(getIntergeList(arrayStr[2]));
                newKlassContent.setRoom(arrayStr[3]);
            }
        }else {
            //虽然没有外教这个多余外国名的空格了，但是还是会存在有一些课程名直接就是带空格的
            int error = arrayStr.length-4;  //误差
            String klassName = "";
            if(error>0){  //一般来说是等于0的,这说明外教佬有空格
                for(int i = 0;i<=error;i++){
                    klassName+=arrayStr[i];
                }
                newKlassContent.setName(klassName);
                newKlassContent.setTeacher(arrayStr[1+error]);
                newKlassContent.setWeekList(getIntergeList(arrayStr[2+error]));
                newKlassContent.setRoom(arrayStr[3+error]);
            }else{//课程名没误差
                newKlassContent.setName(arrayStr[0]);
                newKlassContent.setTeacher(arrayStr[1]);
                newKlassContent.setWeekList(getIntergeList(arrayStr[2]));
                newKlassContent.setRoom(arrayStr[3]);
            }
        }
        return newKlassContent;
    }

    public static  List<Integer> getIntergeList(String weekStr){  //参数为单个数组参数
        List<Integer> integerList = new ArrayList<>();
        String result = weekStr.substring(0,weekStr.indexOf("("));  //得到数据
        if(weekStr.indexOf("单")!=-1){  //属于单周
            String[] listArrays = result.split(",");
            for (String string : listArrays) {
                if (string.indexOf("-") == -1) { // 说明这是一个单数字的,单双周基本不起作用
                    integerList.add(Integer.valueOf(string));
                } else {
                    String[] array = result.split("-");
                    for(int i= Integer.valueOf(array[0]);i<=Integer.valueOf(array[1]);i++){
                        if(2*i-1<=Integer.valueOf(array[1])){
                            integerList.add(2*i-1);
                        }else{
                            break;
                        }
                    }
                }
            }
        }else if(weekStr.indexOf("双")!=-1){  //属于双周
            String[] listArrays = result.split(",");
            for (String string : listArrays) {
                if (string.indexOf("-") == -1) { // 说明这是一个单数字的,单双周基本不起作用
                    integerList.add(Integer.valueOf(string));
                } else {
                    String[] array = result.split("-");
                    for(int i= Integer.valueOf(array[0]);i<=Integer.valueOf(array[1]);i++) {
                        if (2 * i <= Integer.valueOf(array[1])) {
                            integerList.add(2 * i);
                        } else {
                            break;
                        }
                    }
                 }
            }
        }else{
            integerList = StrToListForIntUtil.getList(result);
        }
        return integerList;
    }
}
